package com.rabbitmq.rabbitmqextensions.listener;

import com.rabbitmq.client.Channel;
import com.rabbitmq.rabbitmqextensions.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class QosListener {

    /**
     * 消费者1
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = Constants.QOS_QUEUE)
    public void listener1(Message message, Channel channel) throws IOException {
        String messageInfo = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        log.info("消费者 1 接收到消息: {}, deliveryTag: {}", messageInfo, deliveryTag);
        try {
            Thread.sleep(2000);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {

            channel.basicNack(deliveryTag, false, true);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 消费者2
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = Constants.QOS_QUEUE)
    public void listener2(Message message, Channel channel) throws IOException {
        String messageInfo = new String(message.getBody());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        log.info("消费者 2 接收到消息: {}, deliveryTag: {}", messageInfo, deliveryTag);
        try {
            Thread.sleep(1000);
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {

            channel.basicNack(deliveryTag, false, true);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
